using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using trx2html;

namespace RidoTasks
{
    public class trx2html : Task
    {
        /// <summary>
        /// Gets or sets the files containing
        /// Visual Studio trx data.
        /// </summary>
        [Required]
        public ITaskItem[] TrxFiles { get; set; }

        public ITaskItem OutputDirectory { get; set; }

        public ITaskItem ReportFileName { get; set; }

        /// <summary>
        /// Gets the files generated from the conversion.
        /// </summary>
        [Output]
        public ITaskItem[] ConvertedFiles { get; private set; }

        public override bool Execute()
        {
            LogHeaderMessage();

            var convertedFiles = new List<ITaskItem>();

            bool hasFailure = false;

            foreach (ITaskItem trxFile in TrxFiles)
            {
                String fileName = trxFile.ItemSpec;
                if (!File.Exists(fileName))
                {
                    Log.LogError("TRX File not found {0}", fileName);
                    hasFailure = true;
                    continue;
                }

                try
                {
                    Log.LogMessage("Creating HTML Report from TRX file: {0}", fileName);
                    ReportGenerator.LogMessageProvider = (fmt,args)=>{
                        Log.LogMessage(fmt,args);
                    };
                    var htmFile = ReportGenerator.GenerateReport(fileName,
                        (OutputDirectory==null)?null:OutputDirectory.ItemSpec,
                        (ReportFileName== null)?null:ReportFileName.ItemSpec);
                }
                catch (Exception ex)
                {
                    Log.LogErrorFromException(ex);
                    hasFailure = true;
                    continue;
                }
            }
            return !hasFailure;
        }

        private void LogHeaderMessage()
        {
            Log.LogMessage("trx2html  Creates HTML reports of VSTS TRX TestResults . (c)rido'11");
            Log.LogMessage("version: {0} \n", Assembly.GetExecutingAssembly().GetName().Version.ToString());            
        }     
    }
}
